/**
 * 输入一个数组，返回具有ListNode的对象
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
    console.log(JSON.stringify(list1));
    let arr = [].concat(flat(list1), flat(list2));
    arr.sort((a, b) => a - b);

    const n = listNode(arr);

    return n;
};

function flat(listNode) {
    if (listNode == null) {
        return [];
    }

    let arr = [];
    let node = listNode;
    console.log(`flat: node is ${JSON.stringify(node)}`);
    do {
        arr.push(node.val);
        node = node.next;
    } while (!!node && !!node.next);
    if (!!node) {
        arr.push(node.val);
    }

    console.log(`flat complete: arr is ${JSON.stringify(arr)}`);
    return arr;
}

function listNode(arr) {
    console.log(`[listNode] arr is ${JSON.stringify(arr)}`);
    if (!arr || arr.length < 1) {
        return null;
    }

    let ret = {
        val: null,
        next: null,
    };
    let temp = ret;
    for (let i = 0; i < arr.length; i++) {
        temp.val = arr[i];
        temp.next = null;
        if (i < arr.length - 1) {
            temp.next = {
                val: null,
                next: null,
            };
        }

        temp = temp.next;
    }
    console.log(`[listNode complete] ret is ${JSON.stringify(ret)}`);
    return ret;
}

// test
// console.log(JSON.stringify(listNode([1, 2, 3, 4])));

let listNode1 = {
    val: 1,
    next: { val: 2, next: { val: 3, next: { val: 4, next: null } } },
};

let a = new ListNode(1, new ListNode(2, null));

console.log(flat(a));
